package com.yunshipei.ui.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.yunshipei.base.BaseLoginActivity;
import com.yunshipei.common.Globals;
import com.yunshipei.common.manager.EnterConfig;
import com.yunshipei.common.net.api.HubInterfaceApi;
import com.yunshipei.common.net.api.LoginAuthApi;
import com.yunshipei.common.net.converter.JsonConverterFactory;
import com.yunshipei.core.common.XCloudException;
import com.yunshipei.core.manager.XCloudSDKManager;
import com.yunshipei.core.net.EnterClient;
import com.yunshipei.core.utils.FileUtils;
import com.yunshipei.core.utils.NetUtils;
import com.yunshipei.core.utils.SystemUtils;
import com.yunshipei.enterplorer.BuildConfig;
import com.yunshipei.enterplorer.R;
import com.yunshipei.ui.dialog.DialogHelper;
import com.yunshipei.ui.dialog.WaitDialog;
import com.yunshipei.ui.fragment.CompanyNameHistoryFragment;
import com.yunshipei.utils.BaseUtil;
import com.yunshipei.utils.ToastUtils;

import org.json.JSONObject;
import org.reactivestreams.Publisher;

import java.io.File;
import java.util.HashSet;
import java.util.Set;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.OnTextChanged;
import butterknife.OnTouch;
import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;

public class CompanyNameLoginActivity extends BaseLoginActivity implements CompanyNameHistoryFragment.OnFragmentInteraction {

    private static final String HUB_SERVER = "https://hub.enterplorer.com";
    private static final String HUB_TEST_SERVER = "https://hubtest.enterplorer.com";

    @Bind(R.id.et_company_name)
    protected EditText mCompanyNameEt;
    @Bind(R.id.tv_app_viersion)
    protected TextView mAppVersionTv;
    @Bind(R.id.fl_more_company_name)
    protected FrameLayout mCompanyNameHisFl;
    @Bind(R.id.rl_root_view)
    protected RelativeLayout mRootLoginFl;
    @Bind(R.id.rl_company_login_content_edit)
    protected RelativeLayout mContentEditRl;
    @Bind(R.id.iv_clear_company_name)
    protected ImageView mClearTextImg;
    @Bind(R.id.iv_show_more_company_name)
    protected ImageView mShowCompanyNameIv;
    @Bind(R.id.btn_next)
    protected Button mNextBtn;

    private SharedPreferences mNoClearPreferences;
    private Set<String> mCompanyNameHistory;
    private String mCompanyName;
    private WaitDialog mWaitDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_company_name_login);
        ButterKnife.bind(this);
        mNoClearPreferences = getSharedPreferences(Globals.NO_CLEAR_SHP, MODE_PRIVATE);
        mCompanyNameHistory = mNoClearPreferences.getStringSet(Globals.MY_OLD_DOMAIN_NAME_DATAS, new HashSet<String>());
        if (mCompanyNameHistory.size() == 0) {
            mShowCompanyNameIv.setVisibility(View.GONE);
        }
        String companyName = mNoClearPreferences.getString(Globals.SP_COMPANY_HOST, "");
        mCompanyNameEt.setText(companyName);
        mCompanyNameEt.setSelection(TextUtils.isEmpty(companyName) ? 0 : companyName.length());
        mAppVersionTv.setText(BuildConfig.DEBUG ? "内测版" + BuildConfig.VERSION_NAME : BuildConfig.VERSION_NAME);
        final int keyHeight = this.getWindowManager().getDefaultDisplay().getHeight() / 3;
        if (!SystemUtils.isPad(this)) {
            mRootLoginFl.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
                @Override
                public void onLayoutChange(View v, int left, int top, int right, final int bottom, int oldLeft, int oldTop, int oldRight, final int oldBottom) {
                    if (oldBottom != 0 && bottom != 0 && (oldBottom - bottom > keyHeight)) {
                        mRootLoginFl.setPadding(0, 0, 0, 0);
                        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) mContentEditRl.getLayoutParams();
                        if (layoutParams.getRules()[RelativeLayout.ALIGN_PARENT_BOTTOM] == 0) {
                            layoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
                        }
                        mContentEditRl.setLayoutParams(layoutParams);
                        mAppVersionTv.setVisibility(View.INVISIBLE);
                    } else if (oldBottom != 0 && bottom != 0 && (bottom - oldBottom > keyHeight)) {
                        mRootLoginFl.setPadding(0, getResources().getDimensionPixelOffset(R.dimen.login_root_padding), 0, 0);
                        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) mContentEditRl.getLayoutParams();
                        if (layoutParams.getRules()[RelativeLayout.ALIGN_PARENT_BOTTOM] != 0) {
                            layoutParams.removeRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
                        }
                        mContentEditRl.setLayoutParams(layoutParams);
                        mAppVersionTv.setVisibility(View.VISIBLE);
                    }
                }
            });
        } else {
            RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) mContentEditRl.getLayoutParams();
            layoutParams.width = (int) ((BaseUtil.getStandSize(this) * 4) / 5);
            mContentEditRl.setLayoutParams(layoutParams);
        }
    }

    @OnClick({R.id.tv_set_server, R.id.btn_next, R.id.iv_show_more_company_name, R.id.iv_clear_company_name})
    protected void clickEvent(View view) {
        switch (view.getId()) {
            case R.id.tv_set_server:
                startActivity(new Intent(this, EnterplorerURLActivity.class));
                break;
            case R.id.btn_next:
                BaseUtil.hideKeyBoard(this);
                if (!NetUtils.isNetworkAvailable(this)) {
                    ToastUtils.showToast(getString(R.string.net_no_connect));
                } else {
                    mCompanyName = mCompanyNameEt.getText().toString().trim();
                    String pattern = "^([a-z0-9]+[a-z0-9\\-]*?\\.)+(com|cn|net|org|gov|info|la|cc|co)$";
                    boolean isUseful = mCompanyName.matches(pattern);
                    if (!isUseful) {
                        ToastUtils.showToast(getString(R.string.useless_company_code));
                    } else {
                        if (mWaitDialog == null) {
                            mWaitDialog = DialogHelper.getNoCancelableWaitDialog(this, "正在验证企业域名,请稍候...");
                        }
                        mWaitDialog.show();
                        loginCompanyName();
                    }
                }
                break;
            case R.id.iv_show_more_company_name:
                BaseUtil.hideKeyBoard(this);
                if (mCompanyNameHistory.size() > 0) {
                    Fragment fragment = getSupportFragmentManager().findFragmentByTag(CompanyNameHistoryFragment.class.getName());
                    if (fragment == null) {
                        fragment = CompanyNameHistoryFragment.newInstance();
                    }
                    CompanyNameHistoryFragment companyNameHistoryFragment = (CompanyNameHistoryFragment) fragment;
                    if (!fragment.isAdded()) {
                        getSupportFragmentManager().beginTransaction().add(R.id.fl_more_company_name, companyNameHistoryFragment, companyNameHistoryFragment.getClass().getName()).commit();
                    }
                    if (mCompanyNameHisFl.getVisibility() == View.VISIBLE) {
                        mCompanyNameHisFl.setVisibility(View.GONE);
                    } else if (mCompanyNameHisFl.getVisibility() == View.GONE) {
                        mCompanyNameHisFl.setVisibility(View.VISIBLE);
                    }
                }
                break;
            case R.id.iv_clear_company_name:
                mCompanyNameEt.setText("");
                break;
        }
    }

    private void loginCompanyName() {
        final String configIP = mNoClearPreferences.getString(Globals.MANUAL_PROXY, "");
        final int configPort = mNoClearPreferences.getInt(Globals.MANUAL_PROXY_PORT, 0);
        //1、判断是否手动配置过manager地址和manager的代理，如果手动配置过，直接使用手动配置的，如果没有手动配置过，则从hub获取
        Flowable.just(mNoClearPreferences.getString(Globals.MANUAL_BASE_URL, "")).flatMap(new Function<String, Publisher<JSONObject>>() {
            @Override
            public Publisher<JSONObject> apply(String configManagerServer) throws Exception {
                if (TextUtils.isEmpty(configManagerServer)) {
                    OkHttpClient client = EnterClient.getInstances().getHubClient();
                    String hubServer = "";
                    String server = FileUtils.readFile(Environment.getExternalStorageDirectory().getPath() + File.separator + "_ysp_hub_server.txt");
                    if (BuildConfig.DEBUG && !TextUtils.isEmpty(server)) {
                        hubServer = server.trim();
                    } else {
                        hubServer = TextUtils.isEmpty(mCompanyName) ? HUB_SERVER : ((mCompanyName.startsWith("ysptest-") || mCompanyName.startsWith("www.ysptest-")) ? HUB_TEST_SERVER : HUB_SERVER);
                    }
                    final HubInterfaceApi api = new Retrofit.Builder().client(client).baseUrl(hubServer).addCallAdapterFactory(RxJava2CallAdapterFactory.create()).addConverterFactory(JsonConverterFactory.create()).build().create(HubInterfaceApi.class);
                    return api.authHub(mCompanyName).flatMap(new Function<JSONObject, Publisher<JSONObject>>() {
                        @SuppressLint("CommitPrefEdits")
                        @Override
                        public Publisher<JSONObject> apply(JSONObject jsonObject) throws Exception {
                            String managerServer = jsonObject.optString("manager_url");
                            if (!TextUtils.isEmpty(managerServer)) {
                                String proxy = jsonObject.optString("manager_proxy", "");
                                String proxyIP = "";
                                int port = 0;
                                if (!TextUtils.isEmpty(proxy)) {
                                    int index = proxy.indexOf(":");
                                    if (index != -1) {
                                        String[] array = proxy.split(":");
                                        proxyIP = array[0];
                                        port = Integer.parseInt(array[1]);
                                    }
                                }
                                if (managerServer.endsWith("/")) {
                                    managerServer = managerServer.substring(0, managerServer.length() - 1);
                                }
                                SharedPreferences.Editor editor = mNoClearPreferences.edit().putString(Globals.SP_HUB_GET_SERVER, managerServer);
                                //优先使用本地配置的代理
                                if (!TextUtils.isEmpty(configIP) && 0 != configPort) {
                                    proxyIP = configIP;
                                    port = configPort;
                                    editor.putString(Globals.SP_HUB_GET_PROXY_IP, "").putInt(Globals.SP_HUB_GET_PROXY_PORT, 0);
                                } else {
                                    editor.putString(Globals.SP_HUB_GET_PROXY_IP, proxyIP).putInt(Globals.SP_HUB_GET_PROXY_PORT, port);
                                }
                                editor.apply();
                                EnterClient.getInstances().initManagerClient(managerServer + "/v2/newLogin", proxyIP, port);
                                OkHttpClient mClient = EnterClient.getInstances().getManagerClient();
                                LoginAuthApi authApi = new Retrofit.Builder().client(mClient).baseUrl(managerServer).addCallAdapterFactory(RxJava2CallAdapterFactory.create()).addConverterFactory(JsonConverterFactory.create()).build().create(LoginAuthApi.class);
                                return authApi.authCompany(mCompanyName);
                            }
                            return Flowable.error(new XCloudException(jsonObject.optString("message", "未知hub错误")));
                        }
                    });
                }
                //使用手动设置的manager地址直接登录manager的第一步
                String proxyIP = "";
                int proxyPort = 0;
                if (!TextUtils.isEmpty(configIP) && 0 != configPort) {
                    proxyIP = configIP;
                    proxyPort = configPort;
                }
                EnterClient.getInstances().initManagerClient(configManagerServer + "/v2/newLogin", proxyIP, proxyPort);
                OkHttpClient client = EnterClient.getInstances().getManagerClient();
                LoginAuthApi authApi = new Retrofit.Builder().client(client).baseUrl(configManagerServer).addCallAdapterFactory(RxJava2CallAdapterFactory.create()).addConverterFactory(JsonConverterFactory.create()).build().create(LoginAuthApi.class);
                return authApi.authCompany(mCompanyName);
            }
        }).flatMap(new Function<JSONObject, Publisher<Boolean>>() {
            @SuppressLint({"CommitPrefEdits", "ApplySharedPref"})
            @Override
            public Publisher<Boolean> apply(JSONObject jsonObject) throws Exception {
                int status = jsonObject.optInt("status", 0);
                if (status == 1) {
                    JSONObject data = jsonObject.optJSONObject("data");
                    String companyID = data.optString("companyId");
                    String companyLogo = data.optString("iconUrl");
                    String placeHolder = data.optString("placeHolder");
                    String themeCode = data.optString("themeCode");
                    SharedPreferences.Editor editor = mNoClearPreferences.edit();
                    editor.putString(Globals.SP_COMPANY_ID, companyID)
                            .putString(Globals.SP_COMPANY_LOGO, companyLogo)
                            .putString(Globals.SP_COMPANY_HOST, mCompanyName)
                            .putString(Globals.SP_COMPANY_THEME_CODE, themeCode)
                            .putString(Globals.SP_COMPANY_PLACE_HOLDER, placeHolder);
                    EnterConfig.getInstance().setThemeCode(themeCode);
                    if (!mCompanyNameHistory.contains(mCompanyName)) {
                        mCompanyNameHistory.add(mCompanyName);
                        editor.putStringSet(Globals.MY_OLD_DOMAIN_NAME_DATAS, mCompanyNameHistory);
                    }
                    editor.commit();
                    return Flowable.just(true);
                } else {
                    return Flowable.error(new XCloudException(jsonObject.optString("message", "接口异常，请联系管理员...")));
                }
            }
        }).subscribeOn(Schedulers.io()).unsubscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) throws Exception {
                        mWaitDialog.dismiss();
                        startActivity(new Intent(CompanyNameLoginActivity.this, SystemUtils.isPad(CompanyNameLoginActivity.this) ? LoginActivity.class : H5LoginActivity.class));
                        finish();
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        mWaitDialog.dismiss();
                        ToastUtils.showToast(XCloudSDKManager.getInstance().generateError(throwable));
                    }
                });
    }

    @OnTextChanged(R.id.et_company_name)
    protected void onTextChanged(Editable editable) {
        mClearTextImg.setVisibility(editable.length() > 0 ? View.VISIBLE : View.GONE);
        mNextBtn.setAlpha(editable.length() > 0 ? 1.0f : 0.6f);
        mNextBtn.setEnabled(editable.length() > 0);
    }

    @OnTouch({R.id.rl_root_view, R.id.et_company_name})
    protected boolean rootViewTouchEvent(View view) {
        if (mCompanyNameHisFl.getVisibility() == View.VISIBLE) {
            mCompanyNameHisFl.setVisibility(View.GONE);
        }
        switch (view.getId()) {
            case R.id.rl_root_view:
                BaseUtil.hideKeyBoard(this);
                return false;
            case R.id.et_company_name:
                return false;
        }
        return false;
    }

    @Override
    public void itemSelected(String companyName) {
        mCompanyNameEt.setText(companyName);
        mCompanyNameEt.setSelection(companyName.length());
        mCompanyNameHisFl.setVisibility(View.GONE);
    }

    @Override
    public void closeItem(String companyName) {
        mCompanyNameHistory.remove(companyName);
        if (mCompanyNameHistory.size() == 0) {
            mShowCompanyNameIv.setVisibility(View.GONE);
        }
    }
}
